<?php 
class kdtrace_dhl extends Controller {
	
	function track( $tracknum , $lang = "en_US"){
		if($lang=="ch"){$langset = "zh";} else {$langset = "en";};
		$getdata = array(
			"AWB"			=>	$tracknum,
			"countryCode"	=>	"g0",
			"languageCode"	=>	$langset,
			"_"				=>	time()
		);
		$url = "http://www.dhl.com/shipmentTracking?" . http_build_query($getdata, '', '&');
		
		$ch = curl_init();
		curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_HEADER, 0);
		curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_TIMEOUT, 15);
		curl_setopt($ch, CURLOPT_HTTPHEADER, array(
			'Referer: http://www.dhl.com/en/express/tracking.html',
			'User-Agent: Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/33.0.1750.154 Safari/537.36' 
		));
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 1);

		$result = curl_exec($ch);
        curl_close($ch);
		$result = json_decode($result);
		$rtndata = array('tracknum'=>$tracknum,'header'=>array(),'err'=>array(),'eventList'=>array());

		if( $result->errors[0]->code > "1"){
			$rtndata['err']['errcode'] = '1';
			$rtndata['err']['errmsg'] = $result->errors[0]->label ;
		}else{
			$result = $result->results[0];
			$rtndata['err']['errcode'] = '0';	
	
			$rtndata['header']['shipFrom']      = $result->origin->value;
			$rtndata['header']['shipTo']    = $result->destination->value;
			$rtndata['header']['keyStatus']        = $result->delivery->status;
			$rtndata['header']['DetailStatus']     = $result->description;
			$i = 0;
			foreach( $result->checkpoints as $tlist){
				$tt =  strtotime($tlist->date . " " . $tlist->time);
				$rtndata['eventList'][$i] = array(
					"date"			=> date('Y-m-d',$tt),
					"time"			=> date('h:i:s',$tt),
					"utime"			=> $tt,
					"status"		=> $tlist->description,
					"location"		=> $tlist->location
				);
				$i++;
			}
		}
		$rtndata['eventList'] = array_reverse( $rtndata['eventList'] );
		return $rtndata;
	}
	
}

?>